package com.example.config;

import com.alibaba.fastjson.JSON;
import com.example.entity.vo.UsrRole;
import com.example.service.ISysUserService;
import com.example.ulit.JwtUtil;
import com.example.ulit.UsrIdByToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@Component
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    ISysUserService sysUserService;

    @Resource
    UsrIdByToken usrIdByToken;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException {
        User user = (User)authentication.getPrincipal();
        UsrRole usrRole = sysUserService.searchAllByUsrName(user.getUsername());
        String token = JwtUtil.generateToken(usrRole);
        if(JwtUtil.verify()){
            Map<String,Object> map = JwtUtil.parseToken(token);
            usrIdByToken.setStringRedisTemplate(token,map.get("usrId").toString());
        }
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("code","200");
        resultMap.put("token",token);
        response.getWriter().print(JSON.toJSON(resultMap));
    }
}